/**
 * @author:         lirenyi
 * @update:         2016-06-10
 * @Description:    应用路由文件
*/

define(function (require, exports, modules) {
	
	//配置baseUrl
    var baseUrl = document.getElementById('main').getAttribute('data-baseurl');
	
	var Backbone = require('backbone'),
		util = require('util'),
		BaseController = require('assets/js/baseController');

	//路由表 
    var routesMap = {
		'loading': 'loading/controller.loading',
        'login': 'login/controller.login',
        'home': 'home/controller.home',
        'farm': 'farm/controller.farm',
        'friendFarm': 'friendFarm/controller.friendFarm',
        'entry': 'entry/controller.entry',	//选择登陆、注册页面
        'register': 'register/controller.register',	//开放注册
        'share': 'share/controller.share',
        /*养鸡日志*/
        'chickensLog':'chickensLog/controller.chickensLog',
       /* 交易记录*/
        'records':'records/controller.records',
    	'default' : 'loading/controller.loading'
    };

    var Router = Backbone.Router.extend({
    	routes:{
    		'': 'navigator',
            ':p1': 'navigator',
            ':p1/:p2': 'navigator',
            ':p1/:p2/:p3': 'navigator',
            ':p1/:p2/:p3/:p4': 'navigator',
            ':p1/:p2/:p3/:p4/p5': 'navigator',
            ':p1/:p2/:p3/:p4/p5/p6': 'navigator',
            ':p1/:p2/:p3/:p4/p5/p6/p7': 'navigator',
            ':p1/:p2/:p3/:p4/p5/p6/p7(/*path)': 'navigator',
    	},
    	initialize: function(){
            util.baseController = util.baseController || new BaseController();
            util.baseController.on('change:router', function() {
            	if(this.attributes.view){
            		this.get('view').stopListening();
            		this.get('view').remove();
            	}
            	var url = arguments[1];
				var _this = this, 
					viewPath = url[0], 
					params = [].slice.call(url, 1);
				require([ viewPath ], function(Controller) {
					_this.controller = new Controller({
						rp : params,
						baseController:_this
					});
				});
          	});
        },
        navigator: function(){
            var parameters = arguments.length>1 ? [].slice.call(arguments, arguments.length-1) : [],
                viewPath = [].slice.call(arguments,0,arguments.length-1).join('/');
            if(typeof routesMap[viewPath]=='undefined')viewPath = 'default';

            util.currentHash = Backbone.history.getHash();
            util.baseController.set('router',_.union([baseUrl+routesMap[viewPath]],parameters));
        }
    });
    var router = new Router();
    
    return router;
});
